# coding:utf-8
import subprocess
import yaml
import os

PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)


def up_cmd(command):
    cmd = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, encoding='gbk')
    msg = cmd.stdout.read()
    # print(msg)
    cmd.terminate()
    msg2 = cmd.poll()
    return print(msg, msg2)


def get_config(config_path):
    try:
        with open(config_path, encoding='utf-8') as f:
            x = yaml.load(f, Loader=yaml.FullLoader)
            return x
    except:
        return print("==get_config找不到配置文件,检查下路径==\nconfig_path:", config_path)


def cmd_jdk():
    # print(f'setx JAVA_HOME "{get_config()[0]+JAVA_HOME}" /M')
    # print(r'setx path "%path%;%%JAVA_HOME%%\bin" /M')
    # print(r'setx classpath .;%%JAVA_HOME%%\lib\dt.jar;%%JAVA_HOME%%\lib\tools.jar /M')
    up_cmd(f'setx JAVA_HOME "{get_config()[0] + JAVA_HOME}" /M')
    for a in range(len(get_config()) - 1):
        a += 1
        up_cmd(get_config()[a])


if __name__ == '__main__':
    JAVA_HOME = input(r"jdk的安装路径,例如：D:\test files\jdk1.8.0_144：")
    config_path = PATH("../Automated_install_jdk/config.yaml")
    cmd_jdk()
